 #define _CRT_SECURE_NO_WARNINGS 1

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution {
public:
    ListNode* removeNthFromEnd(ListNode* head, int n) {
        ListNode* newhead = new ListNode(0, head);
        ListNode* fast = head;
        ListNode* slow = newhead;
        //1.先让快指针向前走n步
        for (int i = 0; i < n; i++)
            fast = fast->next;
        //2.再按双指针法让快指针走到null
        while (fast)
        {
            fast = fast->next;
            slow = slow->next;
        }

        slow->next = slow->next->next;
        ListNode* ans = newhead->next;
        delete newhead;
        return ans;
    }
};